/**
 * 
 */
package com.home.emp.web;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import java.util.Iterator;

import com.home.emp.dao.EmployeeDAO;
import com.home.emp.dvo.Employee;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xprk339
 *
 */
public class NewEmployeeController extends SimpleFormController {

	private static Logger logger = Logger.getLogger(NewEmployeeController.class);
	private EmployeeDAO employeeDAO;
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Employee employee = null;
		Object idObj = request.getParameter("id");
		if (idObj != null){
			employee = getEmployeeDAO().getEmployee(new Integer(idObj.toString()));
		}else{
			employee = new Employee();
		}
		return employee;
	}
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		// TODO Auto-generated method stub
		List employees = null;
		Employee employee = (Employee) command;
		logger.info("Selected User name : "+employee.getEmpName());
		logger.info("Selected User Addr : "+employee.getEmpAddress());
		getEmployeeDAO().saveEmployee(employee);
		return super.onSubmit(request, response, command, errors);
	}
	
	private void printEmployees(List emps) {
		for (Iterator iter = emps.iterator();iter.hasNext();){
			Employee emp = (Employee) iter.next();
			logger.info(emp);
		}
	}
	public EmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}
	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}
}
